package token

import (
	"context"
	"strconv"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetTokenByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetTokenByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTokenByIdLogic {
	return &GetTokenByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetTokenByIdLogic) GetTokenById(in *backend.UUIDReq) (*backend.TokenInfo, error) {
	if len(in.Id) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	var id uint64
	if i, err := strconv.ParseInt(in.Id, 10, 64); err != nil {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	} else {
		id = uint64(i)
	}

	res, err := l.svcCtx.SysToken.FindOne(l.ctx, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.TokenInfo{
		Id:        pointy.GetPointer(res.ID),
		Uuid:      pointy.GetPointer(res.UUID),
		Token:     pointy.GetPointer(res.Token),
		Source:    pointy.GetPointer(res.Source),
		Status:    pointy.GetPointer(uint32(res.Status)),
		ExpiredAt: pointy.GetPointer(modelx.FormatNullDotTime(res.ExpiredAt, "")),
		CreatedAt: pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt: pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
	}, nil
}
